<template>
  <div class="pdf-preview">
    <div class="pdf-wrap">
      <vue-pdf-embed
        :source="state.source"
        :style="scaleFun"
        class="vue-pdf-embed"
        :page="state.pageNum"
      />
    </div>
    <div class="page-tool">
      <div class="page-tool-item" @click="lastPage">上一页</div>
      <div class="page-tool-item" @click="nextPage">下一页</div>
      <div class="page-tool-item">{{ state.pageNum }}/{{ state.numPages }}</div>
      <div class="page-tool-item" @click="pageZoomOut">放大</div>
      <div class="page-tool-item" @click="pageZoomIn">缩小</div>
    </div>
  </div>
</template>
<!--封装PDF预览组件   created by jzw  created at 2023-07-14-->
<script setup>
import VuePdfEmbed from "vue-pdf-embed";
import { createLoadingTask } from "vue3-pdfjs/esm"; // 获得总页数
const props = defineProps({
  pdfUrl: {
    type: String,
    required: true,
  },
});

const state = reactive({
  source: props.pdfUrl, //预览pdf文件地址
  pageNum: 1, //当前页面
  scale: 1, // 缩放比例
  numPages: 0, // 总页数
});
const { source, pageNum, scale, numPages } = toRefs(state);
const scaleFun = computed(() => `transform:scale(${scale.value})`);
function lastPage() {
  if (pageNum.value > 1) {
    pageNum.value -= 1;
  }
}
function nextPage() {
  if (pageNum.value < numPages.value) {
    pageNum.value += 1;
  }
}
function pageZoomOut() {
  if (scale.value < 2) {
    scale.value += 0.1;
  }
}
function pageZoomIn() {
  if (scale.value > 1) {
    scale.value -= 0.1;
  }
}

onMounted(() => {
  //const loadingTask = createLoadingTask(source.value);
  createLoadingTask(source.value)
    .promise.then((pdf) => {
      //console.log(pdf);
      numPages.value = pdf.numPages;
    })
    .catch((err) => {
      console.log("加载pdf文件失败", err);
    });
});
</script>
<style scoped lang="scss">
.pdf-preview {
  position: relative;
  height: 100vh;
  padding: 20px 0;
  box-sizing: border-box;
  background-color: e9e9e9;
}
.pdf-wrap {
  overflow-y: auto;
}
.vue-pdf-embed {
  text-align: center;
  width: 515px;
  border: 1px solid #e5e5e5;
  margin: 0 auto;
  box-sizing: border-box;
}

.page-tool {
  position: absolute;
  bottom: 35px;
  padding-left: 15px;
  padding-right: 15px;
  display: flex;
  align-items: center;
  background: rgb(66, 66, 66);
  color: white;
  border-radius: 19px;
  z-index: 100;
  cursor: pointer;
  margin-left: 50%;
  transform: translateX(-50%);
}
.page-tool-item {
  padding: 8px 15px;
  padding-left: 10px;
  cursor: pointer;
}
</style>
